package HTTP

import (
	"SQL/FSDB"
	"net/http"
)

func deleteGroupMember(w http.ResponseWriter, req *http.Request) {

	var resCode = http.StatusOK
	var msg = ""
	var res interface{}
	defer func() {
		writeResult(w, resCode, msg, res)
	}()

	groupID := req.FormValue("groupID")

	ok := false
	if ok, resCode, msg = isValidID(groupID, "GroupID"); !ok {
		if resCode == errInvalidID {
			msg = mInvalidGroupID
		}
		return
	}

	req.ParseForm()
	maxLen := 20
	count := 0
	memberIDs := make([]string, 0)
	for _, memberID := range req.Form["memberID"] {

		if ok, resCode, msg = isValidID(memberID, "MemberID"); !ok {
			msg = mInvalidMemberID
			return
		}
		memberIDs = append(memberIDs, memberID)
		count++
		if count >= maxLen {
			msg = "每次删除成员的数量为 0~20 ！"
			resCode = errInvalidArgLength
			return
		}
	}

	errCode, errMsg := deleteGroupMemberFromDB(groupID, memberIDs)
	msg = errMsg
	if errCode != Success {
		resCode = errCode
		return
	}
}

func deleteGroupMemberFromDB(groupID string, memberIDs []string) (errCode int, errMsg string) {

	delMemberSQL := `DELETE FROM members WHERE userid = $1;`
	tx, err := FSDB.BeginTx()
	if err != nil {
		tx.Rollback()
		return errDBExecFailed, err.Error()
	}
	for _, memberID := range memberIDs {
		_, err := FSDB.ExecTx(tx, delMemberSQL, memberID)
		if err != nil {
			tx.Rollback()
			return errDBExecFailed, err.Error()
		}
	}
	tx.Commit()
	return Success, "删除群成员成功！"
}
